<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true" :model="searchInfo">
        <el-form-item label="分组">
          <el-input v-model="searchInfo.groupName" placeholder="分组" />
        </el-form-item>
		<el-form-item label="路径">
		  <el-input v-model="searchInfo.path" placeholder="路径" />
		</el-form-item>
        <el-form-item label="请求">
          <el-select v-model="searchInfo.method" clearable placeholder="请选择" style="width: 140px;">
            <el-option
              v-for="item in methodOptions"
              :key="item.value"
              :label="`${item.label}(${item.value})`"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
		<el-form-item label="是否需要授权">
		  <el-select v-model="searchInfo.needAuthority" clearable placeholder="请选择" style="width: 90px;">
		    <el-option
		      v-for="item in isnotOptions"
		      :key="item.value"
		      :label="`${item.label}`"
		      :value="item.value"
		    />
		  </el-select>
		</el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button size="small" icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button size="small" type="primary" icon="plus" @click="openDialog('add')">新增</el-button>
      </div>
      <el-table :data="tableData" max-height="450">
        <!-- <el-table-column
          type="selection"
          width="55"
        /> -->
        <!-- <el-table-column align="left" label="id" min-width="60" prop="ID" /> -->
        <el-table-column align="left" label="分组" min-width="100" prop="groupName" />
        <el-table-column align="left" label="名称" min-width="150" prop="name" />
        <el-table-column align="left" label="路径" min-width="250" prop="path" />
        <el-table-column align="left" label="方法" min-width="80" prop="method" />
		<el-table-column align="left" label="是否保存日志" min-width="100" prop="logToDb" >
          <template #default="scope">
            <!-- <div>
              {{ scope.row.logToDb == 1 ? "是" : "否" }}
            </div> -->
			<div v-for="item in isnotOptions"><span v-if="item.value === scope.row.logToDb">{{item.label}}</span></div>
          </template>
        </el-table-column>
		<el-table-column align="left" label="是否需要授权" min-width="100" prop="needAuthority" >
		  <template #default="scope">
		    <!-- <div>
		      {{ scope.row.needAuthority == 1 ? "是" : "否" }}
		    </div> -->
			<div v-for="item in isnotOptions"><span v-if="item.value === scope.row.needAuthority">{{item.label}}</span></div>
		  </template>
		</el-table-column>
        <el-table-column align="left" label="备注" min-width="200" prop="remark" />

        <el-table-column align="left" fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button
              icon="edit"
              size="small"
              type="text"
              @click="editResourceFunc(scope.row)"
            >编辑</el-button>
            <el-button
              icon="delete"
              size="small"
              type="text"
              @click="deleteResourceFunc(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          :current-page="pageNumber"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>

    </div>

    <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" :title="dialogTitle">
      <warning-bar title="新增资源，需要在角色管理内配置权限才可使用" />
      <el-form ref="resourceForm" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="分组" prop="groupName">
          <el-input v-model="form.groupName" autocomplete="off" />
        </el-form-item>
		<el-form-item label="名称" prop="name">
		  <el-input v-model="form.name" autocomplete="off" />
		</el-form-item>
		<el-form-item label="路径" prop="path">
          <el-input v-model="form.path" autocomplete="off" />
        </el-form-item>
        <el-form-item label="方法" prop="method">
          <el-select v-model="form.method" placeholder="请选择" style="width:100%">
            <el-option
              v-for="item in methodOptions"
              :key="item.value"
              :label="`${item.label}(${item.value})`"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否保存日志" prop="logToDb">
          <el-select v-model="form.logToDb" placeholder="请选择" style="width:100%">
            <el-option
              v-for="item in isnotOptions"
              :key="item.value"
              :label="`${item.label}`"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
		<el-form-item label="是否需要授权" prop="needAuthority">
		  <el-select v-model="form.needAuthority" placeholder="请选择" style="width:100%">
		    <el-option
		      v-for="item in isnotOptions"
		      :key="item.value"
		      :label="`${item.label}`"
		      :value="item.value"
		    />
		  </el-select>
		</el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="closeDialog">取 消</el-button>
          <el-button size="small" type="primary" @click="enterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Resource',
}
</script>

<script setup>
import {
  getResourceList,
  saveResource,
  deleteResource
} from '@/api/resource'
import { getDict } from '@/utils/dictionary'
import warningBar from '@/components/warningBar/warningBar.vue'
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const form = ref({
  groupName: '',
  name: '',
  path: '',
  method: 'POST',
  logToDb: 1,
  needAuthority: 1,
  remark: ''
})
const methodOptions = ref([])

const isnotOptions = ref([])

const type = ref('')
const rules = ref({
  groupName: [
    { required: true, message: '请输入组名称', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入资源介绍', trigger: 'blur' }
  ],
  path: [{ required: true, message: '请输入资源路径', trigger: 'blur' }],
  method: [
    { required: true, message: '请选择请求方式', trigger: 'blur' }
  ]
})

const pageNumber = ref(1)
const total = ref(0)
const pageSize = ref(20)
const tableData = ref([])
const searchInfo = ref({})

const onReset = () => {
  searchInfo.value = {}
}
// 搜索
const onSubmit = () => {
  getTableData()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  pageNumber.value = val
  getTableData()
}

// 查询
const getTableData = async() => {
	// alert(pageSize.value)
  const table = await getResourceList({ pageNumber: pageNumber.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
  }
}

const initPage = async() => {
	{
		  var op = await getDict("resource_method")
		  if(op){
		  	methodOptions.value = op
		  }
	}
	{
		  var op = await getDict("isnot")
		  if(op){
		  	isnotOptions.value = op
		  }
	}
	getTableData()
}

initPage()

// 弹窗相关
const resourceForm = ref(null)
const initForm = () => {
  resourceForm.value.resetFields()
  form.value = {
	  groupName: '',
	  name: '',
	  path: '',
	  method: 'POST',
	  logToDb: 1,
	  needAuthority: 1,
	  remark: ''
  }
}

const dialogTitle = ref('新增资源')
const dialogFormVisible = ref(false)
const openDialog = (key) => {
  switch (key) {
    case 'add':
      dialogTitle.value = '新增资源'
      break
    case 'edit':
      dialogTitle.value = '编辑资源'
      break
    default:
      break
  }
  type.value = key
  dialogFormVisible.value = true
}
const closeDialog = () => {
  initForm()
  dialogFormVisible.value = false
}

const editResourceFunc = async(row) => {
  form.value = row
  openDialog('edit')
}

const enterDialog = async() => {
  resourceForm.value.validate(async valid => {
    if (valid) {
      switch (type.value) {
        case 'add':
          {
            const res = await saveResource(form.value)
            if (res.code === 0) {
              ElMessage({
                type: 'success',
                message: '添加成功',
                showClose: true
              })
            }
            getTableData()
            closeDialog()
          }

          break
        case 'edit':
          {
            const res = await saveResource(form.value)
            if (res.code === 0) {
              ElMessage({
                type: 'success',
                message: '编辑成功',
                showClose: true
              })
            }
            getTableData()
            closeDialog()
          }
          break
        default:
          // eslint-disable-next-line no-lone-blocks
          {
            ElMessage({
              type: 'error',
              message: '未知操作',
              showClose: true
            })
          }
          break
      }
    }
  })
}

const deleteResourceFunc = async(id) => {
  ElMessageBox.confirm('此操作将永久删除所有角色下该资源, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async() => {
      const res = await deleteResource({"id":id})
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '删除成功!'
        })
        if (tableData.value.length === 1 && pageNumber.value > 1) {
          pageNumber.value--
        }
        getTableData()
      }
    })
}

</script>

<style scoped lang="scss">
.button-box {
  padding: 10px 20px;
  .el-button {
    float: right;
  }
}
.warning {
  color: #dc143c;
}
</style>
